/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Cita_View_Add.java
 *
 * Created on 26/05/2012, 04:35:18 PM
 */


/*
 * Tareas:
 * Solo se deberian poder modificar las citas que no han pasado, a futuro. Las citas con fecha anterios solo se deberian consultar
 * Solo se deberian poder eliminar las citas futuras y/o cuyo estado sea asignado
 */

package v;

import beans.Cita;
import beans.dao.CitaDAO;
import c.PlanillasController;
import core.constructor.constructor;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;
import tools.DatosComboBox;

/**
 *
 * @author Usuario
 */
public class Cita_View_Add extends javax.swing.JPanel {
    private static final int TIME = 15;

    private constructor c;
    private LinkedList<String> id_cita = new LinkedList<String>();
    private String id_paciente = null;
    private String id_medico;
//    private String campoPK;
    private PlanillasController controller = new PlanillasController();
    private String mod = "";
    private String llave = "";
    private DatosComboBox cbx;
    private DefaultListModel listModel = new DefaultListModel();

    private static final String ESTADO_CITA = "1";
    
       
    /** Creates new form Cita_View_Add */
    public Cita_View_Add(Object... e) {
        initComponents();
        
        cNombresMedico.setEditable(false);
        cApellidosMedico.setEditable(false);
        fechaCita.setEditable(false);
        citas.setModel(listModel);
        
        //        jHoraCita.setEnabled(false);
        //        //cambiar el color del componente para que no sea "tan gris"
        //
        //        JSpinner.DateEditor de = new JSpinner.DateEditor(jHoraCita, "hh:mm a");
        //        jHoraCita.setEditor(de);
        
        
        
        config(e);
        actualizarEtiqTotal();
        
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        cApellidos = new javax.swing.JTextField();
        jFind = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        cNombres = new javax.swing.JTextField();
        jXTitledSeparator1 = new org.jdesktop.swingx.JXTitledSeparator();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jXTitledSeparator2 = new org.jdesktop.swingx.JXTitledSeparator();
        cNombresMedico = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        cApellidosMedico = new javax.swing.JTextField();
        jXTitledSeparator3 = new org.jdesktop.swingx.JXTitledSeparator();
        jLabel8 = new javax.swing.JLabel();
        cbMotivo = new javax.swing.JComboBox();
        jLabel9 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        textObservacion = new javax.swing.JTextArea();
        bGuardar = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jLabel11 = new javax.swing.JLabel();
        fechaCita = new org.jdesktop.swingx.JXDatePicker();
        jLabel12 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        citas = new javax.swing.JList();
        bAgregaCita = new javax.swing.JButton();
        bLimpiaLista = new javax.swing.JButton();
        bBorraCita = new javax.swing.JButton();
        lTotalCita = new javax.swing.JLabel();

        cApellidos.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N

        jFind.setIcon(new javax.swing.ImageIcon(getClass().getResource("/core/img/busqueda32.png"))); // NOI18N
        jFind.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jFindActionPerformed(evt);
            }
        });

        jLabel4.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel4.setText("Nombres");

        cNombres.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        cNombres.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cNombresActionPerformed(evt);
            }
        });

        jXTitledSeparator1.setFont(new java.awt.Font("Tahoma", 1, 15)); // NOI18N
        jXTitledSeparator1.setHorizontalTextPosition(javax.swing.SwingConstants.LEADING);
        jXTitledSeparator1.setTitle("Datos Paciente");

        jLabel6.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel6.setText("Motivo");

        jLabel7.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel7.setText("Apellidos");

        jXTitledSeparator2.setFont(new java.awt.Font("Tahoma", 1, 15)); // NOI18N
        jXTitledSeparator2.setHorizontalTextPosition(javax.swing.SwingConstants.LEADING);
        jXTitledSeparator2.setTitle("Datos Medico");

        cNombresMedico.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        cNombresMedico.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cNombresMedicoActionPerformed(evt);
            }
        });

        jLabel5.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel5.setText("Nombres");

        cApellidosMedico.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N

        jXTitledSeparator3.setFont(new java.awt.Font("Tahoma", 1, 15)); // NOI18N
        jXTitledSeparator3.setHorizontalTextPosition(javax.swing.SwingConstants.LEADING);
        jXTitledSeparator3.setTitle("Detalles cita");

        jLabel8.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel8.setText("Apellidos");

        cbMotivo.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        cbMotivo.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                cbMotivoItemStateChanged(evt);
            }
        });

        jLabel9.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel9.setText("Observaciones");

        textObservacion.setColumns(20);
        textObservacion.setLineWrap(true);
        textObservacion.setRows(5);
        jScrollPane1.setViewportView(textObservacion);

        bGuardar.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        bGuardar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/core/img/guardar32.png"))); // NOI18N
        bGuardar.setText("Guardar");
        bGuardar.setEnabled(false);
        bGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bGuardarActionPerformed(evt);
            }
        });

        jButton3.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jButton3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/core/img/cancelar32.png"))); // NOI18N
        jButton3.setText("Cancelar");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jLabel11.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel11.setText("Fecha");

        fechaCita.setFormats("dd-MM-yyyy");

        jLabel12.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel12.setText("Citas");

        citas.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        jScrollPane2.setViewportView(citas);

        bAgregaCita.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        bAgregaCita.setIcon(new javax.swing.ImageIcon(getClass().getResource("/core/img/add24.png"))); // NOI18N
        bAgregaCita.setEnabled(false);
        bAgregaCita.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bAgregaCitaActionPerformed(evt);
            }
        });

        bLimpiaLista.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        bLimpiaLista.setText("c");
        bLimpiaLista.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bLimpiaListaActionPerformed(evt);
            }
        });

        bBorraCita.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        bBorraCita.setIcon(new javax.swing.ImageIcon(getClass().getResource("/core/img/remove24.png"))); // NOI18N
        bBorraCita.setEnabled(false);
        bBorraCita.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bBorraCitaActionPerformed(evt);
            }
        });

        lTotalCita.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        lTotalCita.setText("Duración total cita: 15 min");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addComponent(jXTitledSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 463, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(176, 176, 176)
                        .addComponent(jXTitledSeparator2, javax.swing.GroupLayout.DEFAULT_SIZE, 384, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(478, 478, 478)
                        .addComponent(bGuardar, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jXTitledSeparator3, javax.swing.GroupLayout.DEFAULT_SIZE, 1023, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel11)
                                .addGap(39, 39, 39)
                                .addComponent(fechaCita, javax.swing.GroupLayout.DEFAULT_SIZE, 411, Short.MAX_VALUE))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(0, 316, Short.MAX_VALUE)
                                .addComponent(lTotalCita, javax.swing.GroupLayout.PREFERRED_SIZE, 170, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addComponent(jLabel12)
                                .addGap(46, 46, 46)
                                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 411, Short.MAX_VALUE)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(bAgregaCita, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                            .addComponent(bBorraCita, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(bLimpiaLista, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
                        .addGap(4, 4, 4)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel9)
                                .addGap(13, 13, 13)
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 401, Short.MAX_VALUE))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel6)
                                .addGap(61, 61, 61)
                                .addComponent(cbMotivo, 0, 401, Short.MAX_VALUE))))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel4)
                                .addGap(18, 18, 18)
                                .addComponent(cNombres, javax.swing.GroupLayout.PREFERRED_SIZE, 1, Short.MAX_VALUE)
                                .addGap(18, 18, 18)
                                .addComponent(jFind, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addComponent(jLabel8)
                                .addGap(22, 22, 22)
                                .addComponent(cApellidos, javax.swing.GroupLayout.DEFAULT_SIZE, 417, Short.MAX_VALUE)))
                        .addGap(56, 56, 56)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel7)
                                .addGap(46, 46, 46)
                                .addComponent(cApellidosMedico, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel5)
                                .addGap(42, 42, 42)
                                .addComponent(cNombresMedico, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE)))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(11, 11, 11)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jXTitledSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jXTitledSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(cNombres, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jFind, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(cNombresMedico, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(3, 3, 3)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel4)
                            .addComponent(jLabel5))))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(8, 8, 8)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(cApellidosMedico, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(6, 6, 6)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel8)
                                    .addComponent(jLabel7)))))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(11, 11, 11)
                        .addComponent(cApellidos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(18, 18, 18)
                .addComponent(jXTitledSeparator3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel12)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 91, Short.MAX_VALUE)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, 0, 0, Short.MAX_VALUE)
                                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                                .addGap(6, 6, 6)
                                                .addComponent(jLabel9))
                                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                                .addGap(1, 1, 1)
                                                .addComponent(bAgregaCita, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                .addComponent(bBorraCita, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)))
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(bLimpiaLista)))
                                .addGap(2, 2, 2)))
                        .addGap(3, 3, 3)))
                .addGap(4, 4, 4)
                .addComponent(lTotalCita)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(fechaCita, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel6))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(1, 1, 1)
                        .addComponent(jLabel11))
                    .addComponent(cbMotivo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(21, 21, 21)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(bGuardar, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(25, 25, 25))
        );
    }// </editor-fold>//GEN-END:initComponents

private void jFindActionPerformed(java.awt.event.ActionEvent evt) {                                      

    //TODO no mostrar pacientes inactivos
    SeleccionadorIU select = new SeleccionadorIU("SELECT id_paciente, id_tipodocumento, identificacion, "
            + "nombres, apellidos FROM paciente where estado != 0", "CÓDIGO,TIPO,CEDULA,NOMBRES,APELLIDOS", c, this.getClass().getName(), "cargar");
//    select.setBounds(0, 0, 453, 189);         
    select.setVisible(true);         
    Map<String, String> datos = select.getDatosSelect();
    if (!datos.isEmpty()) {             
        cargar(datos);
        
    }

}        

private void cNombresActionPerformed(java.awt.event.ActionEvent evt) {
                                             
}
        

private void cNombresMedicoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cNombresMedicoActionPerformed
 // TODO add your handling code here:
}//GEN-LAST:event_cNombresMedicoActionPerformed

    private void cbMotivoItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_cbMotivoItemStateChanged
    }
// TODO add your handling code here:}//GEN-LAST:event_cbMotivoItemStateChanged

    private void bGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bGuardarActionPerformed
/*
         *        
        prepararTransaccion();     }//GEN-LAST:event_bGuardarActionPerformed
*/
        HashSet<Cita> citasAgendadas = new HashSet<Cita>();
        if(listModel.size()>0 && !id_paciente.isEmpty()){
            for (int i = 0; i < listModel.size(); i++) {
                Cita cita = (Cita) listModel.get(i);
                System.out.println("Id cita:" + cita.getIdCita());
                citasAgendadas.add(cita);
            }
            boolean correcto = CitaDAO.guardarCitas(citasAgendadas, id_paciente, 
                    ESTADO_CITA, cbx.getKeyCitaMotivo(cbMotivo),  //cbx.getKeyCitaEstado(cbEstado)
                    textObservacion.getText());
            if(correcto){
                c.informarUsuario("ok[Asignacion de citas]  Se guardo "
                        + "correctamente la información");
                bGuardar.setEnabled(false);
                return;
            }
            
        }
        c.informarUsuario("error[¡Error al asignar citas!]  "
                + "Debe seleccionar un paciente y agendar "
                + "por lo menos un horario de los disponibles");
    }
    
    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
         if (c != null) {
            c.goBack("Cita_View_Grid");
        }else{
             Logger.getLogger(Cita_View_Add.class.getName()).log(Level.WARNING, "No es posible ir a la interfaz anterior, constructor null");
         }
    }
        /*
         * 
         System.out.println("Fecha = " + cFecha.getDate());     }//GEN-LAST:event_jButton3ActionPerformed
*/

    private void actualizarEtiqTotal() {
        Integer total = TIME * listModel.getSize();
        lTotalCita.setText(String.format("Duración total cita: %d min", total));
    }

        private void bAgregaCitaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bAgregaCitaActionPerformed
            String sql = String.format("select cita.id_cita, medico.nombres, medico.apellidos, "
                    + "planilla_horario.fecha_agendada, to_char(cita.hora, 'HH12:MI AM') "
                    + "from estado_cita, planilla_horario natural join medico, cita "
                    + "where cita.estado = estado_cita.id_estado "
                    + "and cita.id_planilla_horario = planilla_horario.id_planilla_horario and cita.estado = 0 and cita.id_paciente is null "
                    + "and planilla_horario.fecha_agendada = '%s' and planilla_horario.id_medico = '%s' "
                    + "and (planilla_horario.fecha_agendada > current_date or cita.hora > current_time) "
                    + "order by id_cita asc;",
                    fechaCita.getDate().toString(), id_medico);

            SimpleDateFormat parser = new SimpleDateFormat("kk:mm");
            SimpleDateFormat formater = new SimpleDateFormat("hh:mm a");

            SeleccionadorIU select = new SeleccionadorIU(sql, "ID,NOMBRES,"
                    + "APELLIDOS,FECHA,HORA", c, this.getClass().getName(), "cargar");
            select.setBounds(0, 0, 453, 189);
            select.setVisible(true);
            Map<String, String> datos = select.getDatosSelect();
            if (!datos.isEmpty()) {
                try {
                    String hora = formater.format(parser.parse(datos.get("HORA")));
                    Cita citaActual = new Cita(Integer.valueOf(datos.get("ID")));
                    citaActual.setHora(hora);
                    if (!listModel.contains(citaActual)) {
                        if (!listModel.isEmpty()) {
                            Cita citaAnter = (Cita) listModel.lastElement();
                            Cita primerCita = (Cita) listModel.firstElement();
                            if (citaAnter.getIdCita().equals(citaActual.getIdCita() - 1)) {
                                listModel.addElement(citaActual);
                            } else if (primerCita.getIdCita().equals(citaActual.getIdCita() + 1)) {
                                listModel.insertElementAt(citaActual, 0);
                            } else {
                                JOptionPane.showMessageDialog(c,
                                        "Solo se pueden asignar varias citas si son consecutivas",
                                        "Atención!",
                                        JOptionPane.WARNING_MESSAGE);
                            }
                        } else {
                            listModel.addElement(citaActual);
                        }
                        actualizarEtiqTotal();
                    }
                } catch (ParseException ex) {
                    Logger.getLogger(Cita_View_Add.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }//GEN-LAST:event_bAgregaCitaActionPerformed

    private void bBorraCitaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bBorraCitaActionPerformed
        final Integer selectedIndex = citas.getSelectedIndex();

        if (0 != selectedIndex && !selectedIndex.equals(listModel.getSize() - 1)) {
            JOptionPane.showMessageDialog(c,
                    "Solo se puede eliminar la primer o última cita de la lista",
                    "Error al eliminar",
                    JOptionPane.ERROR_MESSAGE);
            return;
        }

        String mensaje = String.format("¿Esta seguro que desea remover la cita de %s",
                listModel.get(selectedIndex));

        if (JOptionPane.OK_OPTION == JOptionPane.showConfirmDialog(c, mensaje)) {
            listModel.remove(selectedIndex);
            bBorraCita.setEnabled(false);
            actualizarEtiqTotal();
        }
    }//GEN-LAST:event_bBorraCitaActionPerformed

private void bLimpiaListaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bLimpiaListaActionPerformed
// TODO add your handling code here:
    if (JOptionPane.OK_OPTION == JOptionPane.showConfirmDialog(c, "Estar seguro de "
            + "limpiar la lista de citas?")) {
        listModel.clear();
    }

}//GEN-LAST:event_bLimpiaListaActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton bAgregaCita;
    private javax.swing.JButton bBorraCita;
    private javax.swing.JButton bGuardar;
    private javax.swing.JButton bLimpiaLista;
    private javax.swing.JTextField cApellidos;
    private javax.swing.JTextField cApellidosMedico;
    private javax.swing.JTextField cNombres;
    private javax.swing.JTextField cNombresMedico;
    private javax.swing.JComboBox cbMotivo;
    private javax.swing.JList citas;
    private org.jdesktop.swingx.JXDatePicker fechaCita;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jFind;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private org.jdesktop.swingx.JXTitledSeparator jXTitledSeparator1;
    private org.jdesktop.swingx.JXTitledSeparator jXTitledSeparator2;
    private org.jdesktop.swingx.JXTitledSeparator jXTitledSeparator3;
    private javax.swing.JLabel lTotalCita;
    private javax.swing.JTextArea textObservacion;
    // End of variables declaration//GEN-END:variables

    private void config(Object[] e) {
        if (e.length > 0) {
            try {
                c = (constructor) e[0];

                //Configura la Interfaz para el Modo en el que fue invocado
                cbx = new DatosComboBox();
                llenarCombos();
                configModo((String) e[1], (String) e[2]);

            } catch (Exception exc) {
                System.err.println("(config())Error de Asignacion , compruebe el numero de Parametros que envia .. " + exc.getMessage());
                exc.printStackTrace();
            }
        }
    }

    private void configModo(String m, String key) {
        mod = m;
        System.out.println("Clave error: " + key);
        String SQL_BUSCAR = String.format(
                "select medico.nombres, medico.apellidos, paciente.nombres, paciente.apellidos, motivo_cita.descripcion, "
                + "estado_cita.descripcion, planilla_horario.fecha_agendada, cita.hora, cita.observacion, planilla_horario.id_medico,"
                + "paciente.id_paciente "
                + "from estado_cita, planilla_horario natural join medico, cita left join paciente on (cita.id_paciente = paciente.id_paciente)"
                + "left outer join motivo_cita on (cita.id_motivo = motivo_cita.id_motivo_cita) "
                + "where cita.estado = estado_cita.id_estado "
                + "and cita.id_planilla_horario = planilla_horario.id_planilla_horario and cita.id_cita = '%s';", key);

        if (!mod.equals("")) {

            if (!mod.equals("INSERT")) {
                this.llave = key;
                id_cita.add(key);
                c.setLabelAccion("Crear Nuevo Paciente");

//                campoPK = "id_cita = " + this.llave;
            }

            if (mod.equals("SELECT")) {
                System.out.println("mod = " + mod);
                System.out.println("key = " + key);
                estadoComponentes(false);
                c.setLabelAccion("Consulta Cita");
                setCita(controller.buscar(SQL_BUSCAR), key);

            } else if (mod.equals("UPDATE")) {
                System.out.println("mod = " + mod);
                System.out.println("key = " + key);

                String sql = "select fecha_agendada, hora_inicio from cita "
                        + "natural join planilla_horario where id_cita = '%s'";

                //Agregar verificación para que no se pueda modificar una cita "pasada"
                id_cita.add(key);
                c.setLabelAccion("Asignar Cita");
                Object[][] buscar = controller.buscar(SQL_BUSCAR);
                setCita(buscar, key);
                bGuardar.setText("Actualizar");
                boolean esCitaModificable = esCitaModificable((String) buscar[0][6],
                        (String) buscar[0][7]);

                estadoComponentes(esCitaModificable);
                bGuardar.setEnabled(esCitaModificable);
                bAgregaCita.setEnabled(esCitaModificable);
//                bLimpiaLista.setEnabled(esCitaModificable);

                if (esCitaModificable) {
                    citas.addMouseListener(new MouseAdapter() {
                        @Override
                        public void mouseClicked(MouseEvent e) {
                            bBorraCita.setEnabled(true);
                        }
                    });
                } else {
                    c.setToolTip("help", "La Cita no se puede modificar, "
                            + "la fecha corresponde a una Fecha pasada o ya ha "
                            + "sido asignada.");
                }
            }
        }

    }

    private void llenarCombos() {
//        cbEstado.setModel(new javax.swing.DefaultComboBoxModel(cbx.cbCitaEstado()));
        cbMotivo.setModel(new javax.swing.DefaultComboBoxModel(cbx.cbCitaMotivo()));
    }

    private void estadoComponentes(boolean b) {
        cNombres.setEditable(b);
        cApellidos.setEditable(b);
        cbMotivo.setEditable(b);
//        cbEstado.setEditable(b);
        textObservacion.setEditable(b);
        jFind.setEnabled(b);
        citas.setEnabled(b);

        bLimpiaLista.setEnabled(b);
    }

    private void setCita(Object[][] buscar, String id) {

        SimpleDateFormat parser = new SimpleDateFormat("kk:mm");
        SimpleDateFormat formater = new SimpleDateFormat("hh:mm a");
        SimpleDateFormat formatoDeFecha = new SimpleDateFormat("yy-MM-dd");


        cNombresMedico.setText(buscar[0][0].toString());
        cApellidosMedico.setText(buscar[0][1].toString());
        cNombres.setText((String) buscar[0][2]);
        cApellidos.setText((String) buscar[0][3]);
        //cbMotivo.setSelectedItem(cbx.getValueCitaMotivo(buscar[0][4].toString()));//si no funcionan los de abajo, cambiar consulta
        //cbEstado.setSelectedItem(cbx.getValueCitaEstado(buscar[0][5].toString()));
        cbMotivo.setSelectedItem((String) buscar[0][4]);
//        cbEstado.setSelectedItem((String)buscar[0][5]);
        textObservacion.setText((String) buscar[0][8]);
        id_medico = (String) buscar[0][9];

        id_paciente = (String) buscar[0][10];
        System.out.println("Idpaciente::: " + id_paciente.isEmpty());

        try {
            fechaCita.setDate(formatoDeFecha.parse(buscar[0][6].toString()));
//            jHoraCita.setValue(formatoDeHora.parse(buscar[0][7].toString()));
            String hora = formater.format(
                    parser.parse(buscar[0][7].toString()));
            Cita horaCita = new Cita(Integer.valueOf(id));
            horaCita.setHora(hora);
            listModel.addElement(horaCita);
        } catch (ParseException ex) {
            System.out.println(ex);
        }
    }

    private void cargar(Map<String, String> datosSelect) {
        cNombres.setText(datosSelect.get("NOMBRES"));
        cApellidos.setText(datosSelect.get("APELLIDOS"));
        id_paciente = datosSelect.get("CÓDIGO");
    }

//    private void prepararTransaccion(String idCita) {
//        String tablaBD = "cita";
//
//        StringBuilder sqlAndRestricciones = new StringBuilder();
//        StringBuilder camposBD = new StringBuilder();
//        StringBuilder valoresBD = new StringBuilder();
////
//        //sqlAndRestricciones.append("Codigo cita@id_cita='" + id_cita.toLowerCase() + "'[-(0,0)]&");
//        //TODO asignar las restricciones
//        sqlAndRestricciones.append("Paciente cita@id_paciente='" + id_paciente + "'[-(0,0)]&");
//        sqlAndRestricciones.append("Motivo cita@id_motivo='" + cbx.getKeyCitaMotivo(cbMotivo) + "'[-(0,0)]&");
//        sqlAndRestricciones.append("Observaciones@observacion='" + textObservacion.getText() + "'[-(0,0)]&");
//        sqlAndRestricciones.append("Estado cita@estado='" + cbx.getKeyCitaEstado(cbEstado) + "'[-(0,0)]");
//        
//        String pk = "id_cita = " + idCita;
//        
//        String mensajeUsuario = controller.prepararTransaccion(tablaBD, sqlAndRestricciones, mod, "La cita", pk);
//
//        c.informarUsuario(mensajeUsuario);
//    }
    private boolean esCitaModificable(String fecha, String hora) {
        SimpleDateFormat s = new SimpleDateFormat("yy-MM-dd kk:mm");
        String test = fecha + " " + hora;
        Date result = new Date();
        Date compa = new Date();

        boolean esMod = false;

        try {
            result = s.parse(test);
            esMod = !(result.before(compa));
        } catch (ParseException ex) {
            Logger.getLogger(Borrarme.class.getName()).log(Level.SEVERE, "ParseException ", ex);
        }
        return esMod && id_paciente.isEmpty();
    }
}
